package com.zyk.leetcode;

import java.util.*;

/**
 * @author zhangsan
 * @date 2021/4/3 20:07
 */
public class J06 {


   public static class ListNode {
       int val;
       ListNode next;
       ListNode(int x) { val = x; }
   }

    /** https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/ */
    public static int[] reversePrint(ListNode head) {
        if(head == null) {
            return new int[0];
        }
        Deque<Integer> stack = new ArrayDeque<>();
        ListNode cur = head;
        while (cur != null) {
            stack.addLast(cur.val);
            cur = cur.next;
        }
        int[] ans = new int[stack.size()];
        int i = 0;
        while (!stack.isEmpty()) {
            ans[i++] = stack.pollLast();
        }
        return ans;
    }

    public static int[] reversePrint2(ListNode head) {
        // 反转链表
        ListNode cur = head;
        ListNode pre = null;
        ListNode next = null;
        int size = 0;
        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
            size++;
        }

        int[] ans = new int[size];
        int i = 0;
        while (pre != null) {
            ans[i++] = pre.val;
            pre = pre.next;
        }
        return ans;
    }

    // for test
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next = new ListNode(6);
        head.next.next.next.next.next.next = new ListNode(7);
        int[] ints = reversePrint(head);
        int[] ints2 = reversePrint2(head);
        System.out.println(Arrays.toString(ints));
        System.out.println(Arrays.toString(ints2));
    }

}
